<template>
  <!-- 添加素材 -->
  <div class="p-2">
    <el-card>
      <template v-slot:header>
        <div class="muonseu">
          <div class="clearfix">
            <span>{{ huinseu }}</span>
          </div>
          <div>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button type="danger" @click="close">关 闭</el-button>
          </div>
        </div>
      </template>
      <el-form ref="goodsFormRef" :model="queryParams" label-width="120px">
        <el-row>
          <el-col :span="8" class="huinsec">
            <el-form-item label="封面" prop="cover">
              <!-- 封面添加上传 -->
              <el-upload 
                class="avatar-uploader" 
                action="#" 
                :http-request="upuonsetics" 
                :show-file-list="false"
              >
                <img v-if="queryParams.cover" :src="queryParams.cover" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
              <!-- 进度条 -->
              <el-progress v-show="isShow" :text-inside="true" :stroke-width="15" :percentage="progressShu" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="素材类型" prop="type" style="width: 300px;">
              <el-select placeholder="请选择" v-model="queryParams.type" clearable>
                <el-option v-for="dict in options" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="商品卖点" prop="sellingPoint" v-if="queryParams.type == 'GOODS'">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容"
                v-model="queryParams.sellingPoint" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="8" class="numSty">
            <el-form-item label="排序" prop="sort">
              <el-input-number placeholder="请输入" v-model="queryParams.sort" controls-position="right" :precision="0"
                style="width: 200px;" />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
            <div class="flex" v-for="(item, index) in yionsecio" :key="index">
              <el-form-item :label="index == 0 ? '商品卖点' : ''" prop="euinse" style="width: 93%;">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容" v-model="item.cuinseo"
                  clearable />
              </el-form-item>
              <el-button icon="Plus" circle class="ml-3" @click="addWonseuig(index)" />
              <el-button icon="Delete" circle @click="deleteYuionsce(index)" v-if="index" />
            </div>
          </el-col> -->

          <el-col :span="24">
            <div class="flex" v-for="(item, index) in ordersListl" :key="index">
              <!-- :disabled="disabledType" -->
              <el-form-item :label="index == 0 ? '素材标题' : ''" prop="euinse" style="width: 93%;">
                <el-input v-model="item.euinse" placeholder="请输入"></el-input>
              </el-form-item>
              <el-button icon="Plus" circle class="ml-3" @click="addHeaderRow(index)" />
              <el-button icon="Delete" circle @click="deleteHeaderRow(index)" v-if="index" />
            </div>
          </el-col>

          <el-col :span="24">
            <div class="flex" v-for="(item, index) in muisneco" :key="index">
              <el-form-item :label="index == 0 ? '口播台词' : ''" prop="cuiosn" style="width: 93%;">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容" v-model="item.cuiosn"
                  clearable />
              </el-form-item>
              <el-button icon="Plus" circle class="ml-3" @click="addBuionsec(index)" />
              <el-button icon="Delete" circle @click="huonsctui(index)" v-if="index" />
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="AddMaterial">
import upload from "@/utils/upload";//封装的oss自定义图片上传方法
import { addMaterial, getMaterial, updateMaterial } from '@/api/operates/material/index';
import { MaterialForm } from '@/api/operates/material/types';
// 获取toke的方法
import { globalHeaders } from "@/utils/request";


/************************ 引用的oss自定义图片上传和进度条 ******************************/
import axios from 'axios'
import OSS from 'ali-oss'
import { v4 as uuidv4 } from 'uuid'
const bashPath = '/sts';//oss上传地址
const bucket = 'juguanghe'
const region = 'oss-cn-hangzhou'
const progressShu = ref(0) //控制进度条
const isShow = ref(false) //控制上传按钮和进度条的显示


const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const huonseom = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/file/upload'
})

// 接收父组件的参数
const { id } = defineProps({
  id: {}
});
// 顶部标题
const huinseu = ref<string>('')
const disabledType = ref(false)
const initFormData: MaterialForm = {
  cover: '',
  type: '',
  titles: [],
  spokenLines: [],
  sort: 0,
  sellingPoint: '',
}
const data = reactive<PageData<MaterialForm, MaterialForm>>({
  form: { ...initFormData },
  queryParams: {
    cover: '',
    type: '',
    titles: [],
    spokenLines: [],
    sort: 0,
    sellingPoint: '',
  },
  rules: {}
})

const { queryParams, form, rules } = toRefs(data)


const yionsecio = ref([
  { cuinseo: '' }
]);

const ordersListl = ref([
  { euinse: '' }
]);

const muisneco = ref([
  { cuiosn: '' }
]);
const goodsFormRef = ref<ElFormInstance>()
/**
 * 查询的素材类型
 */
const options = [
  {
    value: 'GOODS',
    label: '商品素材',
  },
  {
    value: 'TASK',
    label: '任务素材',
  }
]

/**
 * 查询的启用禁用
 */
const euomurin = [
  {
    value: 1,
    label: '启用',
  },
  {
    value: 0,
    label: '禁用',
  }
]
// 商品卖点 点击加号:添加一行header
const addWonseuig = (index: number) => {
  if (index <= 3) {
    yionsecio.value.push({ cuinseo: '' });
  } else {
    proxy?.$modal.msgWarning(`最多添加五个`)
  }
};

// 商品卖点 点击减号:删除一行header
const deleteYuionsce = (index: number) => {
  yionsecio.value.splice(index, 1);
};
// 素材标题点击加号:添加一行header
const addHeaderRow = (index: number) => {
  if (index <= 3) {
    ordersListl.value.push({ euinse: '' });
  } else {
    proxy?.$modal.msgWarning(`最多添加五个`)
  }
};

// 素材标题点击减号:删除一行header
const deleteHeaderRow = (index: number) => {
  ordersListl.value.splice(index, 1);
};

// 口播台词点击加号:添加一行header
const addBuionsec = (index: number) => {
  if (index <= 3) {
    muisneco.value.push({ cuiosn: '' });
  } else {
    proxy?.$modal.msgWarning(`最多添加五个`)
  }
};

// 口播台词点击减号:删除一行header
const huonsctui = (index: number) => {
  muisneco.value.splice(index, 1);
};

// 自定义封面图片上传方法
const upuonsetics = async (op: any) => {
  // console.log(op.file);
  /******************* 清空图片，进度条隐藏，进度条的进度值清空 ************************/
  queryParams.value.cover = '';
  isShow.value = false;
  progressShu.value = 0;
  /********************************** 自定义的oss方法 *************************************/
  const file = op.file;
  let fileName = file.name;
  let sts = await axios.get(bashPath);
  const client = new OSS({
    region,
    accessKeyId: sts.data.AccessKeyId,
    accessKeySecret: sts.data.AccessKeySecret,
    stsToken: sts.data.SecurityToken,
    bucket,
    // 刷新临时访问凭证的时间间隔，单位为毫秒。
    refreshSTSTokenInterval: 3600 * 1000
  })
  let uuid = uuidv4() + fileName.substring(fileName.lastIndexOf('.'))

  return client.multipartUpload('tantao/' + uuid, file, {
    //p进度条的值
    progress: (p, checkpoint) => {
      isShow.value = true;//显示进度条
      progressShu.value = Number((p * 100).toFixed(0));
    },
    mime: file.type,
  }).then((res: any) => {
    let url = res.res.requestUrls[0];
    if (url.indexOf('?') > -1) {
      queryParams.value.cover = url.substring(0, url.indexOf('?')).replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
      console.log('2222'+ queryParams.value.cover);
      if (progressShu.value == 100) {
        let syinmr = setInterval(() => {
          isShow.value = false;
          clearInterval(syinmr)
        }, 1100)
      }
    } else {
      queryParams.value.cover = url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
      console.log('2222'+ queryParams.value.cover);
      isShow.value = false;
    }
  }).catch((err) => {
    console.log('err', err);
  });
}

const beforeAvatarUpload = (file: any) => {
  // console.log(file.type);
  const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
  const isJPG = type.includes(file.type);
  //检验文件格式
  if (!isJPG) {
    proxy?.$modal.msgError(`图片格式错误!`);
    return false;
  }
}

const guinseyu = async () => {
  if (id) {
    const propertyName = 'euinse';
    const puonseicyi = 'cuiosn';
    const { data } = await getMaterial(id as string | number);
    // console.log(data);

    // 回显封面
    queryParams.value.cover = data.cover;
    // 回显素材类型
    queryParams.value.type = data.type;
    // 回显排序
    queryParams.value.sort = data.sort;
    // 回显商品卖点
    queryParams.value.sellingPoint = data.sellingPoint;
    // 回显素材标题
    ordersListl.value = data.titles.map(item => ({ [propertyName]: item }));
    // 回显口播台词
    muisneco.value = data.spokenLines.map(item => ({ [puonseicyi]: item }));
    // 赋值素材id
    queryParams.value.id = data.id;
  }

}

const getTitle = () => {
  if (id) {
    huinseu.value = '素材修改'
    disabledType.value = true
  } else {
    huinseu.value = '素材添加'
  }
}

/**
 * 提交
 */
const submitForm = async () => {
  try {
    // 赋值素材标题
    queryParams.value.titles = ordersListl.value.map(user => user.euinse)
    // 赋值口播台词
    queryParams.value.spokenLines = muisneco.value.map(user => user.cuiosn)
    id ? await updateMaterial(queryParams.value) : await addMaterial(queryParams.value)
    proxy?.$modal.msgSuccess(`${id ? '修改' : '添加'}成功`)
    close()
  } catch (error) {

  }
}

/**
 * 关闭
 */
const close = () => {
  proxy?.$tab.closeOpenPage();
  router.push({ name: "Material" });
}


onMounted(() => {
  guinseyu()
  getTitle()
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 146px;
  height: 146px;
  display: block;
  object-fit: contain;
}

.muonseu {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

:deep(.numSty .el-input-number .el-input__inner) {
  text-align: left;
}

/* oss上传的魔改上传和进度条的样式 */
.el-progress--line {
  margin-top: 8px;
  width: 146px;
}
:deep(.huinsec .el-form-item__content) {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-items: flex-start;
}

:deep(.huinsec .el-form-item--default .el-form-item__content) {
  line-height: 0px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 146px;
  height: 146px;
  text-align: center;
}
</style>